package com.gzc.just.play.last.war.sceneserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.sceneserver.battle.BattleManager;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 离开战斗处理器
 * 处理离开战斗的消息
 */
@Component
public class LeaveBattleHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(LeaveBattleHandler.class);
    
    @Autowired
    private BattleManager battleManager;
    
    private static final int LEAVE_BATTLE = 1003;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        if (playerId == null) {
            logger.error("Player ID not found in context, cannot process leave battle message");
            return;
        }
        
        // 将玩家从战斗中移除
        if (battleManager.removePlayerFromBattle(playerId)) {
            // 发送离开成功响应
            sendLeaveBattleResponse(ctx, true, "Left battle successfully");
            
            logger.info("Player {} left battle", playerId);
        } else {
            // 发送离开失败响应
            sendLeaveBattleResponse(ctx, false, "Not in any battle");
            
            logger.warn("Player {} failed to leave battle", playerId);
        }
    }
    
    private void sendLeaveBattleResponse(ChannelHandlerContext ctx, boolean success, String message) {
        // 实际实现中应该构造并发送离开战斗响应消息
        logger.info("Sending leave battle response: success={}, message={}", success, message);
    }

    @Override
    public int getMessageId() {
        return LEAVE_BATTLE;
    }
    
    @Override
    public String getName() {
        return "LeaveBattleHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}